import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { ListItemGhost2, StyledWrap } from './style'
import StyleChoose from './StyleChoose'
import { StyledView, AddIcon } from './style'
import { initData, StyleData, vmpStyleData } from './interface'
import { DragDropContextProvider, Draggable, Droppable } from '@/plugins/dnd'
import { UserEntity } from '@/api/create/interface'
import { ListItemGhost } from '@/pages/create/createContent/components/DndGhost'
import { VmpMemberEntity } from '../../interface'
import { t } from 'i18next'

export enum VmpTypeEnum {
	'发言方跟随' = 2,
	'管理方跟随' = 3,
	'会议轮询跟随' = 4,
	'单通道轮询' = 6,
	'内容共享跟随' = 7,
}
type ScrollBarProps = {
	/** 是否显示样式选择滚动条 */
	isShowScrollBar?: boolean
	/** 是否只显示一个样式 */
	isShowSingle?: boolean
	/** 样式是否可选择 */
	isBarDisabled?: boolean
	/** 画面合成样式滑轮显示个数 */
	scrollLength?: number
	/** 样式选择事件 */
	onSelect?: (val: number, prev: number) => void
}
type BasicOptionData = { operate?: boolean | 'setting' | 'delete' }

type BoxProps<T> = {
	/** 是否显示样式选择框 */
	isShowBox?: boolean
	/** 样式选择框是否可操作 */
	isBoxDisabled?: boolean
	/** 选择框设置项显示隐藏 */
	/** 只可从外部拖入，不可相互拖拽 */
	onlyDragIn?: boolean
	/** 是否显示加号图标 */
	noAddIcon?: boolean
	/** 样式框修改 */
	onBoxChange?: () => void
} & (T extends { operate: false | 'delete' } ? T : T)

export type VmpViewProps<T extends BasicOptionData> = {
	style: number
	members: Array<VmpMemberEntity>
	disabled?: boolean
} & ScrollBarProps &
	BoxProps<T>
type DropDataMt = UserEntity
interface DropData<T = DropDataMt, K = { [key: string]: any }> {
	data?: {
		mt?: T
	} & K
	from?: string
	index?: number
}
const getStyleData = (style: number) => vmpStyleData.find((item) => item.id === style) ?? vmpStyleData[0]

function VmpView<T extends BasicOptionData>(props: VmpViewProps<T>, ref: any) {
	const {
		style: orgStyle,
		members,
		disabled = false,
		isShowScrollBar = true,
		isShowSingle = false,
		isBarDisabled = false,
		scrollLength = 5,
		onSelect,
		isShowBox = true,
		isBoxDisabled = false,
		operate = true,
		onlyDragIn = false,
		noAddIcon = false,
		onBoxChange,
	} = props
	const [styleData, setStyleData] = useState(vmpStyleData[0]) //当前样式数据
	const [memberList, setMemberList] = useState<Array<VmpMemberEntity>>([])
	const [activeIndex, setActiveIndex] = useState<number | null>(null)
	useEffect(() => {
		let curStyleData = getStyleData(orgStyle)
		let data = new Array(curStyleData.listItemCount)
			.fill({})
			.map((_, index) => members.find((item) => item.chn_idx === getChnidx(index, curStyleData)) ?? initData)
		setStyleData(curStyleData)
		setMemberList(data)
	}, [orgStyle, members])
	const vmpStyleSelect = (id: number) => {
		if (id === styleData.id) return
		onSelect?.(id, styleData.id)
		let curStyleData = getStyleData(id)
		let data = new Array(curStyleData.listItemCount)
			.fill({})
			.map(
				(_, index) =>
					memberList.find(
						(item) => item.chn_idx === getChnidx(index, curStyleData) && item.member_type !== 0
					) ?? initData
			)
		setStyleData(curStyleData)
		setMemberList(data)
	}
	const getChnidx = (index: number, data?: StyleData) => {
		let obj = data ?? styleData
		return obj.order ? obj.order[index] - 1 : index
	}
	const handleDrop = (dataTransfer: DropData, index: number) => {
		let dragFromListName = dataTransfer.from
		let sourceData = dataTransfer.data?.mt
		if (sourceData) {
			let newArr = [...memberList]
			if (dragFromListName === 'memberList') {
				//从用户列表拖拽
				newArr[index] = {
					account: sourceData.account ?? '',
					account_type: sourceData.account_type ?? 1,
					name: sourceData.name,
					portrait: sourceData.portrait,
					conf_e164: sourceData.conf_e164,
					chn_idx: getChnidx(index),
					member_type: 1,
				}
			} else if (dragFromListName === 'vmpItem' && !onlyDragIn) {
				//在风格内部相互拖拽
				let sourceIndex = dataTransfer.data?.index
				if (newArr[index].member_type === 6) return
				if (newArr[index].member_type !== 0) {
					let temp = { ...newArr[index], name: newArr[index].name, chn_idx: getChnidx(sourceIndex) }
					newArr[index] = {
						...newArr[sourceIndex],
						name: newArr[sourceIndex].name,
						chn_idx: getChnidx(index),
					}
					newArr[sourceIndex] = temp
				} else {
					newArr[index] = {
						...newArr[sourceIndex],
						name: newArr[sourceIndex].name,
						chn_idx: getChnidx(index),
					}
					newArr[sourceIndex] = initData
				}
			}
			setMemberList(newArr)
			onBoxChange?.()
		}
	}
	const clearVmpMember = (index: number) => {
		let newArr = [...memberList]
		newArr[index] = initData
		setMemberList(newArr)
		onBoxChange?.()
	}
	useImperativeHandle(ref, () => ({
		getValue() {
			return memberList.filter((i) => !(!i.account && i.member_type === 0))
		},
		getStyle() {
			return styleData.id
		},
	}))
	return (
		<StyledWrap className="vmp-select-box">
			{isShowScrollBar && (
				<StyleChoose
					styleData={styleData}
					onSelect={vmpStyleSelect}
					isShowSingle={isShowSingle}
					disabled={disabled || isBarDisabled}
					scrollLength={scrollLength}
				/>
			)}
			{isShowBox && (
				<DragDropContextProvider>
					<StyledView disabled={disabled || isBoxDisabled}>
						<div className={`vmp-list ${styleData.className}`} data-key={styleData.dataKey}>
							{memberList.map((member, index) => {
								return (
									<div
										key={index}
										datatype={String(getChnidx(index))}
										className={`vmp-list-item ${activeIndex === index ? 'active' : ''}`}
										onMouseEnter={() => setActiveIndex(index)}
										onMouseLeave={() => setActiveIndex(null)}
									>
										<Droppable onDrop={(dataTransfer) => handleDrop(dataTransfer, index)}>
											{(setDroppableRef) => (
												<div ref={setDroppableRef} className="vmp-drop-item">
													{!isBoxDisabled &&
														!disabled &&
														operate &&
														activeIndex === index && (
															<div className="operate">
																{member.member_type !== 0 && (
																	<span
																		className="delete"
																		onClick={() => clearVmpMember(index)}
																	></span>
																)}
															</div>
														)}
													<Draggable
														className="vmp-drag-item"
														canDrag={
															member.member_type !== 0 &&
															member.member_type !== 6 &&
															!isBoxDisabled &&
															!disabled
														}
														dataTransfer={{
															data: { mt: member, index },
															from: 'vmpItem',
														}}
														ghostRender={
															member.member_type === 1 ? (
																<ListItemGhost
																	data={{
																		portrait: member.portrait || '',
																		account_type: member.account_type || 1,
																		isMt: true,
																		name: member.name,
																		isPhone: false,
																		isSimpleCascade: false,
																	}}
																/>
															) : (
																<ListItemGhost2>
																	{t(`${VmpTypeEnum[member.member_type]}`)}
																</ListItemGhost2>
															)
														}
													>
														{member.member_type !== 0 ? (
															<div className="text" title={member.name}>
																{member.name}
															</div>
														) : noAddIcon ? (
															<></>
														) : (
															<AddIcon />
														)}
													</Draggable>
												</div>
											)}
										</Droppable>
									</div>
								)
							})}
						</div>
					</StyledView>
				</DragDropContextProvider>
			)}
		</StyledWrap>
	)
}
export default forwardRef(VmpView) as <T extends BasicOptionData>(
	props: VmpViewProps<T> & { ref?: any }
) => React.ReactElement
